<?php
/**
 * CF_class_com.php includes main auto creation classes
 * This package licenced under GPL
 * @package CFtable
 * @license http://www.gnu.org/licenses/gpl-3.0-standalone.html
 * @copyright Managed Computer Solutions
 */
//  2008-12-19 changed 'showkey' and 'valuekey' to 'showvalue' and 'keyvalue' for drop down and multiple radio options

include_once "CF_support.php";
// Classes
/**
 * CFform is a class will create a form with data input and output from a descriptor
* @package CFtable
 * @author Chris Tyler
 * @version 1.0
 * @CFform is the base class for the an extensable HTML forms.
 * @copyright 2007-2008
 */
class CFform {

	/**
	* @var array $valuesarray A 2D array of values, an array of associative row arrays, valuesarray[<row number>][<column heading>]
	*/
	var $valuesarray;
	/**
	* @var array $fieldspec Array describes data and formatting options
	*/
	var $fieldspec;
    var $pageform;
    var $actionpage;
    var $formname;
    var $selfpage;
    /**
	* @var string $keys string for keys as pulled from Request for edit page
	*/
    var $keys;


    function CFform($the_spec = '',$valuesarray = ''){
        if(is_array($the_spec)){
			$this->fieldspec = $the_spec;
        }
        if(is_array($valuesarray)){
            $this->valuesarray = $valuesarray;
		}
    }


    function set_actionpage($pagename){
		$this->actionpage = $pagename;
	}

 	/**
	 *
     * make_form will create an editable form for the feildset
     * @param string $method Specifies form method, 'get' or 'post'
	 *
	 */
     function make_form($method = 'get', $mode = 'Save'){
         //if(!empty($this->valuesarray)){
    		$outtext = "<form name='form_input' method='$method' action='$this->actionpage'>\n";
    		$currentrow = $this->valuesarray[0];

			//foreach ($currentrow as $col_name => $currentvalue) {
            foreach ($this->fieldspec as $col_name => $currentspec){
                $currentvalue = $currentrow[$col_name];
                if($this->fieldspec[$col_name]['show'] == 'E'){
                    (empty($this->fieldspec[$col_name]['headname']))?$elements[$col_name]['heading'] = $col_name: $elements[$col_name]['heading'] = $this->fieldspec[$col_name]['headname'];
                    $elements[$col_name]['input']= $this->edit_field($this->fieldspec[$col_name],$col_name,$currentvalue,$chgname,$col_name);
                }
                }
            // }

		 //print_r($elements);
		 $outtext .= $this->make_element_div_set($elements, "class='header'", "class='input'");
		 $outtext .= $this->make_keys_hidden();
		 $outtext .= "\n<div class='controls'><input type='submit' value='Save' />";
         $outtext .= "<input type='hidden' name='mode' value='$mode' />";
         $outtext .= "</div>\n</form>\n";
		  //$outtext .= "</div>\n";
	 return $outtext;
	 //}
	}

 	/**
	 *
     * make_element_div_set set will create a set of div for use as a form
     * from an input of an element_set array.  Each row has element_name and value
     * @param array elements An array with [body] and [head] parts where head
     * elements['head'] is the title and elements['body'] is what to put in the cell
     * @param string $headset Settings for heading elements (class name, etc)
     * @param string $bodyset Settings for body elemetns (class naem, etc)
     * @param string $id Settings for name of the div set
	 *
	 */
    function make_element_div_set($elements, $headset, $bodyset){
        foreach ($elements AS $name=>$current){
            $outtext .= "<div id='entry_$name' class='entries'>\n";
            foreach($current AS $key=>$value){

                $outtext .= "<div class='$key'>\n $value </div>\n";
                }
            $outtext .= "</div>\n";
         }

        return $outtext;
    }

 	/**
	 *
     * make_keys_hidden will create a string of key names and values as specified
     * in the fieldspec, in hidden elements (name=name, value=keyvalue).
	 *
	 */
	function make_keys_hidden(){
		foreach($this->fieldspec as $col_name => $colspec){
			if(!empty($colspec['key'] )){
				if(isset($this->keys[$col_name])){ // check if defined and exists in keys array
					$outtext .= " <input type='hidden' name='$col_name' value='" . $this->keys[$col_name] . "' /> ";
				}
			}
		}
		return $outtext;
	}
 	/**
	 *
     * get_keys will fill the $this->keys array with values for each key
     * in the fieldspec, if they are defined.  Returns 1 for all keys found, 0 if not.
	 *
	 */
	function get_keys(){
	//for each column which is a key, get the key and set the keys variable array
    $foundall = true;
	foreach ($this->fieldspec as $col_name => $colspec){
        
        if(!empty($colspec['key'])){
            if((isset($_REQUEST[$col_name])) AND ($_REQUEST[$col_name] != '') ){
                $this->keys[$col_name] = $_REQUEST[$col_name];
                }else{
                   $foundall = false;
                }
            }
		}
		return $foundall;
	}

	function set_name($name){
		$this->form_name = $name;
	}

	function set_selfpage($newpage){
		$this->selfpage = $newpage;
	}

	function make_keys_clause(){
		foreach($this->fieldspec as $col_name => $colspec){
			if(!empty($this->fieldspec[$col_name]['key'] )){
				if(isset($this->keys[$col_name])){ // check if defined and exists in keys array
					$outtext .= " AND $col_name = '" . $this->keys[$col_name] . "' ";
				}else{
					$outtext .= " AND 0 "; // Not all specified keys were defined, so return 0 to kill any results form query
				}
			}
		}
		return $outtext ;
	}
    
	/**
	 *  set_valuesarray Method will set values array to passed array
     * @param array $dataarray  This is array.
	 */
	function set_valuesarray($dataarray){
		$this->valuesarray = $dataarray;
	}

    /**
     * Set FieldSpec Function
     * @param array $thespec - The fieldspec array
     * @param array $thespec [<colname>] - Set for each column, as named in the database query used
     * @param array $thespec [<colname>] ['headname'] (opt) - Name to display on the header for the column.  If not there, will use <colname>
     * @param array $thespec [<colname>] [key] - If set (1), this will be used as a key field for record operations
     * @param array $thespec [<colname>] [show] - If set (1), this column will show in displays.  If 0 or unset, column will not appear
     * @param array $thespec [<colname>] [select] - How to display editable boxes: {T = Text Input, C = Check box (0 or 1), D = drop down)
     * @param array $thespec [<colname>] [list] = array of values (showvalue, keyvalue) to use in drop-down.  Array is of form:  valueslist [<index integer>][<keyvariablename>][<showvariablename>] Where defaults are keyvariablename = 'keyvalue' showvariable='showvalue' unless re-assigned
     * @param array $thespec [<colname>] [showvalue] - (opt)  Re-assignes the <keyvariablename> to the string specified, instead of 'keyvalue'
     * @param array $thespec [<colname>] [keyvalue] - (opt) Re-assignes the <showvariablename> to the string specified, instead of 'showvalue'
     * @param array $thespec [<colname>] [sort] - Specifies if row header will sort or not, {true, false, (or undefined)}
     * @param array $thespec [<colname>] [filter] - Specifies if row is filtered. if set= 'keyword', then will  bet textbox for LIKE '%keyword%' search.  If set (= 1, but not specific setting ), then will filter using spec from edit criteria ([select],[list],)
     */
	function set_fieldspec($thespec){
		$this->fieldspec = $thespec;
	}

    /**
 * edit_field Method will make editable entry element for column
 * according to the feildspec[<column>][filter] specs
 * @param string $column Column to make input element for
 * @param string $elename Element Name
 * @param string $changefunction is onChange, onBlur or onClick function
 * @param string $eleid = element id
 * @param bool $prelist = Create first 'non selected' parameters.  Will output a drop-down with 3 values for a checklist.
 */
function edit_field($descriptor,$elename,$def_value, $changefunction ='', $eleid = '', $prelist = false){
    $rawformat = $descriptor['rawformat'];
    // defaults for list key and value
    $showkey = 'showvalue';
    $valuekey = 'keyvalue';

    $size = '';
    $rows = '';


    if($descriptor['select'] == 'D'){
        $valuesarray = $descriptor['list'];
        if(isset($descriptor['showvalue'])){
            $showkey = $descriptor['showvalue'];
        }
        if(isset($descriptor['keyvalue'])){
            $valuekey = $descriptor['keyvalue'];
        }

        $dd_opts['id'] = $eleid;
        $dd_opts['onchangename'] = $changefunction;

        $select_text = make_array_select($valuesarray, $elename, $valuekey,$showkey,$def_value, 40, $dd_opts, $prelist);
        $field .= "\n$select_text\n";

	}//end if select type 'D' for dropdown select
    // C for checkbox
    else if ($descriptor['select'] == 'C'){
        if(!$prelist){ // if we dont need a thrid 'neither' option, then make a checkbox
            $field .= "<input type='hidden' name='$elename' value='0'>";
            // NOTE:  the above hidden  this does not have an id, only a name, so that the javascript will not catch it using by_id, but the form processing will (using name)
            if($def_value != 0){
                $field .= "<input type='checkbox' name='$elename' id='$eleid' value='1' CHECKED $rawformat onClick=\"$changefunction\" />\n";
            }
            else {
                $field .= "<input type='checkbox' name='$elename' id='$eleid' value='1' $rawformat onClick=\"$changefunction\" />\n";
            }
        }// end no prelist
        else{ // make prelist
            $yesnoarray[1]['keyvalue'] = 0;
            $yesnoarray[1]['showvalue'] = 'No';
            $yesnoarray[2]['keyvalue'] = 1;
            $yesnoarray[2]['showvalue'] = 'Yes';

            $field = make_array_select($yesnoarray, $elename, 'keyvalue','showvalue',$def_value, 40, $dd_opts, $prelist);
        }
    }// end if checkbox type 'C'
    // R for radiobutton
    else if ($descriptor['select'] == 'R'){
        $valuesarray = $descriptor['list'];
        if(isset($descriptor['showvalue'])){
            $showkey = $descriptor['showvalue'];
        }
        if(isset($descriptor['keyvalue'])){
            $valuekey = $descriptor['keyvalue'];
        }
        $dd_opts['id'] = $eleid;
        $dd_opts['onchangename'] = $changefunction;

        $select_text = make_array_radiogroup($valuesarray, $elename, valuekey,$showkey,$$column, 40, $dd_opts, $noselect);
        $field .= "\n$select_text\n";
	}// end if radiobutton
    // T for textbox
    else if($descriptor['select'] == 'T'){
        $size = '';
        if(!empty($changefunction)){
            $blurparam = "onBlur = \"$changefunction\"";
        }
        if(!empty($descriptor['size'])){
            $size = " size='" . $descriptor['size'] . "'";
        }
        $field .= "<input type='text' name='$elename' $size id='$eleid' value='$def_value' $rawformat $blurparam />\n";
    }
    // A for textarea
    else if($descriptor['select'] == 'A'){
        if(!empty($changefunction)){
            $blurparam = "onBlur = \"$changefunction\"";
        }
        if(!empty($descriptor['size'])){
                $cols = " cols='" . $descriptor['size'] . "'";
                }
        if(!empty($descriptor['size'])){
                $rows = " rows='" . $descriptor['rows'] . "'";
                }
        $field .= "<textarea name='$elename' id='$eleid' $cols $rows $blurparam >$def_value</textarea>\n";
    }
    return $field;
}


}

?>